package gdma.hqdes.article.util;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.template.ChartTemplate;
import com.deepoove.poi.template.MetaTemplate;
import com.deepoove.poi.template.PictureTemplate;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFPicture;

import java.util.Optional;
import java.util.function.Predicate;

/**
 * @Author wangyue
 * @Version 3.0
 * @Date 2024-07-30
 */
public class TemplateUtils {

    public static XWPFChart findPlaceheldChart(XWPFTemplate template, Predicate<String> finderByName) {
        Optional<MetaTemplate> chartElement = template.getElementTemplates().stream().filter(e -> e instanceof ChartTemplate && finderByName.test(e.toString())).findFirst();
        return chartElement.isPresent() ? ((ChartTemplate)chartElement.get()).getChart() : null;
    }

    public static XWPFPicture findPlaceheldPicture(XWPFTemplate template, Predicate<String> finderByName) {
        Optional<MetaTemplate> pictureElement = template.getElementTemplates().stream().filter(e -> e instanceof PictureTemplate && finderByName.test(e.toString())).findFirst();
        return pictureElement.isPresent() ? ((PictureTemplate)pictureElement.get()).getPicture() : null;
    }

    private static final double POINTS_TO_PIXELS = 96.0 / 72.0;

    public static int getPictureWidthInPixels(XWPFPicture picture) {
        double widthInPoints = picture.getWidth();
        return (int) Math.round(widthInPoints * POINTS_TO_PIXELS);
    }

    public static int getPictureHeightInPixels(XWPFPicture picture) {
        double heightInPoints = picture.getDepth();
        return (int) Math.round(heightInPoints * POINTS_TO_PIXELS);
    }

}
